package edu.avans.hartigehap.web.util;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import edu.avans.hartigehap.domain.InternetBill;
import edu.avans.hartigehap.domain.Restaurant;
import edu.avans.hartigehap.service.BillService;
import edu.avans.hartigehap.service.RestaurantService;

public class FrontendBillInterceptor extends HandlerInterceptorAdapter {
	final static Logger logger = LoggerFactory.getLogger(FrontendBillInterceptor.class);

	@Autowired
	private RestaurantService restaurantService;
	@Autowired
	private BillService billService;
	

	public boolean preHandle(HttpServletRequest request, 
		HttpServletResponse response, Object handler)
	    throws Exception {

		Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
		try {
			String restaurantName = (String) pathVariables.get("restaurantName");
		 
			Restaurant restaurant = restaurantService.fetchWarmedUp(restaurantName);
			long billId = getBillId(request);
	
			if(billId == -1){
				logger.debug("No Bill Cookie found");
				billId = billService.createInternetBill(restaurantName);
				setBillId(response, billId);
			} else {
				logger.debug("Bill Cookie found: " + billId);
				boolean isFromCurrentRestaurant = false;
				for (InternetBill internetBill : restaurant.getInternetBills()) {
			        if (internetBill.getId().equals(billId) && !internetBill.isSubmitted()) {
						logger.debug("Bill found in Restaurant: " + restaurant.getId());
			        	isFromCurrentRestaurant = true;
			        } else {
						//logger.info("Bill " + internetBill.getId() + " not equal");
			        }
			    }
				if(!isFromCurrentRestaurant){
					logger.debug("Bill not found in Restaurant: " + restaurant.getId() + " creating a new one.");
					billId = billService.createInternetBill(restaurantName);
					logger.debug("Bill created with id: " + billId);
					setBillId(response, billId);
				}
			}
	
			logger.info("BillId: " + billId);
			request.setAttribute("billId", billId);
			//request.getSession().setAttribute("billId", billId);
			return true;
		} catch(NullPointerException e){
			logger.info("restaurantName not found. De mapping is waarschijnlijk verkeerd. De url is niet gemapt aan een Controller. Url=" + request.getRequestURI());
			response.sendError(404);
			//response.sendRedirect("/hartigehapspring/?error=restaurantName not found. De mapping is waarschijnlijk verkeerd. De url is niet gemapt aan een Controller&url=" + request.getRequestURI());
			return false;
		}
	}
	
	public long getBillId(HttpServletRequest request){
		//request.getSession().getValue("billId");
		for (Cookie cookie : request.getCookies()) {
	        if (cookie.getName().equals("billId")) {
	            return Long.parseLong(cookie.getValue());
	        }
	    }
		return -1;
	}
	
	public void setBillId(HttpServletResponse response, Long billId){
		Cookie cookie= new Cookie("billId", billId.toString());
		cookie.setPath("/");
		//cookie.setMaxAge(COOKIE_EXPIRY);
		response.addCookie(cookie);
	}
	
	public static void deleteBillId(HttpServletResponse response){
		logger.debug("Bill Cookie deleted");
		Cookie cookie= new Cookie("billId", "");
		cookie.setPath("/");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

}
